import pickle
import base64
from django_redis import get_redis_connection


def merge_cookie_redis_cart(request,user,response):
    """
    :param request:  爲了獲取cookie數據
    :param user:    爲了獲取redis數據
    :param response: 爲了清楚cookie
    :return:
    """
    # 獲取cookie中的數據
    cookie_cart = request.COOKIES.get("cart")

    # 判斷cookie是否可用
    if not cookie_cart:
        return response

    # 轉換cookie爲字典
    cookie_dict = {}
    if cookie_cart:
        cookie_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

    # 獲取redis數據
    redis_conn = get_redis_connection("cart")

    # 合並數據到redis中
    for sku_id,count_selected in cookie_dict.items():
        redis_conn.hset("cart_%s"%user.id,sku_id,count_selected["count"])
        redis_conn.sadd("cart_selected_%s"%user.id,sku_id)

    # 清除cookie數據
    response.delete_cookie("cart")

    # 返回響應
    return response